'use strict';
import moment = require('moment');
import Sqlite3 = require('../lib/sqlite');
import os = require("os");
var path = os.homedir()
var file = "ts-b16-roller";
let Sqlite = new Sqlite3(path, file);
const db_actuator = `ID INTEGER PRIMARY KEY AUTOINCREMENT,
                        name varchar(45) NOT NULL, 
                        addr varchar(45) NOT NULL,
                        type varchar(8) NOT NULL,
                        groupId INT8 NOT NULL,                        
                        channel INT8 NOT NULL,               
                        mode_driver varchar(11)  NOT NULL,             
                        glsnr REAL NOT NULL, 
                        grssi REAL NOT NULL, 
                        lsnr REAL NOT NULL, 
                        rssi REAL NOT NULL,  
                        gwmode varchar(2) DEFAULT NULL,             
                        swVer varchar(35)  NOT NULL,                     
                        hwVer varchar(45)  NOT NULL,
                        t varchar(45) NOT NULL`;

/*--------------------------------------------------------------------------------------------------- */
/*------------------------------------------1、LoRaActuator设备表---------------------------------------------- */
/*--------------------------------------------------------------------------------------------------- */
/**
 * loRaActuator入网添加到设备表
 * @param {*} addr 
 * @param {*} groupId 
 * @param {*} glsnr 
 * @param {*} grssi 
 * @param {*} lsnr 
 * @param {*} rssi 
 * @param {*} gwmode 
 * @param {*} swVer 
 * @param {*} hwVer 
 * @returns promise 0更新成功，1新增成功
 */
function AddNewActuator(type: string, addr: string, groupId: number, channel: number, mode_driver: string, glsnr: number, grssi: number, lsnr: number, rssi: number, gwmode: string, swVer: string, hwVer: string) {
    // console.log(addr, groupId, channel, mode_driver, glsnr, grssi, lsnr, rssi, gwmode, swVer, hwVer)
    return new Promise((resolve, reject) => {
        let name = `${type}_${addr}_${groupId}_${channel.toString().padStart(2, "0")}`;
        Sqlite.CreateTable(`t_actuator`, db_actuator).then(() => {
            // console.log(`创建表成功`);
            return Sqlite.QueryConditionalDataFromTable(`t_actuator`, `name='${name}'`);
        }).then((params) => {
            // console.log(`查询数据成功`, params);
            if (params.length > 0) {
                // console.log(`设备信息存在，更新信息`);
                return Sqlite.UpdateMultipleParamsIntoTable(`t_actuator`, ["name", "addr", "type", "groupId", "channel", "mode_driver", "glsnr", "grssi", "lsnr", "rssi", "gwmode", "swVer", "hwVer", "t"], [name, addr, type, groupId, channel, mode_driver, glsnr, grssi, lsnr, rssi, gwmode, swVer, hwVer, moment().format("YYYY-MM-DD HH:mm:ss")], `name='${name}'`);
            } else {
                // console.log(`插入数据`);
                return Sqlite.InsertParamsIntoTable(`t_actuator`, `name,addr,type,groupId,channel,mode_driver,glsnr,grssi,lsnr,rssi,gwmode,swVer,hwVer,t`, `'${name}','${addr}','${type}', ${groupId}, ${channel}, '${mode_driver}', ${glsnr}, ${grssi}, ${lsnr}, ${rssi}, '${gwmode}', '${swVer}', '${hwVer}','${moment().format("YYYY-MM-DD HH:mm:ss")}'`);
            }
        }).then(() => {
            resolve(true);
        }).catch((err) => {
            console.log(`\x1b[0;33m${err}\x1b[0;37m`)
            reject(err)
        })

    })
}
setTimeout(()=>{
    Sqlite.CreateTable(`t_actuator`, db_actuator).then(() => {
        console.log(`创建表成功`);
    })
},5000)
interface ActuatorsInfo {
    name: string,
    addr: string,
    groupId: number,
    channel: number,
    mode_driver: string,
    glsnr: number,
    grssi: number,
    lsnr: number,
    rssi: number,
    gwmode: string,
    swVer: string,
    hwVer: string,
    t: string
}
/**
 * 
 * @returns infos || reject 
 */
function QueryAllNewActuatorsInfo(): Promise<any[]> {
    return new Promise((resolve, reject) => {
        Sqlite.QueryConditionalDataFromTable(`t_actuator`, null).then((actuatorsInfo) => {
            let allInfos: Array<ActuatorsInfo> = [];
            let cnt = 0;
            actuatorsInfo.forEach(actuatorInfo => {
                // console.log(actuatorInfo)
                if (Object.keys(actuatorInfo).length > 3) {
                    let ackInfo = {
                        name: actuatorInfo.name,
                        addr: actuatorInfo.addr,
                        groupId: actuatorInfo.groupId,
                        channel: actuatorInfo.channel,
                        mode_driver: actuatorInfo.mode_driver,
                        glsnr: actuatorInfo.glsnr,
                        grssi: actuatorInfo.grssi,
                        lsnr: actuatorInfo.lsnr,
                        rssi: actuatorInfo.rssi,
                        gwmode: actuatorInfo.gwmode,
                        swVer: actuatorInfo.swVer,
                        hwVer: actuatorInfo.hwVer,
                        t: actuatorInfo.t
                    }
                    allInfos.push(ackInfo)
                }
                if (cnt == actuatorsInfo.length - 1) {
                    let ackInfo = allInfos.sort((a, b) => {
                        return a.name.localeCompare(b.name);
                    })
                    resolve(ackInfo);
                }
                cnt++;
            });

        })
    })
}
interface NewActuatorInfo {
    ID: number,
    name: string,
    addr: string,
    type: string,
    groupId: number,
    channel: number,
    mode_driver: string,
    glsnr: number,
    grssi: number,
    lsnr: number,
    rssi: number,
    gwmode: string,
    swVer: string,
    hwVer: string,
    t: string
}
/**
 * 
 * @returns infos || reject 
 */
function QueryAnNewActuatorsInfo(name: string): Promise<NewActuatorInfo | null> {
    return new Promise((resolve, reject) => {
        Sqlite.QueryConditionalDataFromTable(`t_actuator`, `name='${name}'`).then((actuatorInfo: NewActuatorInfo[]) => {
            if (actuatorInfo.length > 0) {
                resolve(actuatorInfo[0]);
            } else {
                resolve(null);
            }

        }).catch((err) => {
            reject(err)
        })
    })
}

/**
 * 
 * @returns infos || reject 
 */
function QueryTwoNewActuatorsInfo(name1: string, name2: string): Promise<ActuatorsInfo[] | null> {
    return new Promise((resolve, reject) => {
        Sqlite.QueryConditionalDataFromTable(`t_actuator`, `name='${name1}' OR name='${name2}' `).then((actuatorInfo) => {
            if (actuatorInfo.length == 2) {
                resolve(actuatorInfo);
            } else {
                resolve(null);
            }

        }).catch((err) => {
            reject(err)
        })
    })
}

/**
 * 
 * @returns infos || reject 
 */
function QueryActuatorsInfosWithType(type: string) {
    return new Promise((resolve, reject) => {
        Sqlite.QueryConditionalDataFromTable(`t_actuator`, `type='${type}'`).then((actuatorInfo: Array<ActuatorsInfo>) => {
            if (actuatorInfo.length>0) {
                resolve(actuatorInfo);
            } else {
                resolve(null);
            }

        }).catch((err) => {
            reject(err)
        })
    })
}
/**
 * 
 * @returns infos || reject 
 */
function QueryActuatorsInfosWithAddr(addr: string): Promise<NewActuatorInfo[] | null> {
    return new Promise((resolve, reject) => {
        Sqlite.QueryConditionalDataFromTable(`t_actuator`, `addr='${addr}'`).then((actuatorInfo: Array<NewActuatorInfo>) => {
            if (actuatorInfo.length > 0) {
                resolve(actuatorInfo);
            } else {
                resolve(null);
            }

        }).catch((err) => {
            reject(err)
        })
    })
}
/**
 * 
 * @returns infos || reject 
 */
function QueryActuatorsInfosWithAddrAndType(addr: string, type: string) {
    return new Promise((resolve, reject) => {
        Sqlite.QueryConditionalDataFromTable(`t_actuator`, `addr='${addr}' AND type='${type}'`).then((actuatorInfo: Array<ActuatorsInfo>) => {
            if (actuatorInfo.length >0) {
                resolve(actuatorInfo);
            } else {
                resolve(null);
            }

        }).catch((err) => {
            reject(err)
        })
    })
}
function DelTheNewActuatorInfo(addr, groupId, channel) {
    let name = `${addr}_${groupId}_${channel.toString().padStart(2, "0")}`;
    return Sqlite.DeleteConditionalDataFromTable(`t_actuator`, `name='${name}'`);
}


function DelAllNewActuatorsInfo() {
    return Sqlite.DeleteConditionalDataFromTable(`t_actuator`, null);
}
export = {
    AddNewActuator,
    QueryAnNewActuatorsInfo,
    QueryTwoNewActuatorsInfo,
    QueryAllNewActuatorsInfo,
    QueryActuatorsInfosWithType,
    QueryActuatorsInfosWithAddr,
    QueryActuatorsInfosWithAddrAndType,
    DelTheNewActuatorInfo,
    DelAllNewActuatorsInfo,
}

